package al54spiralorder;

import java.util.ArrayList;
import java.util.List;

public class SpiralOrder54 {

    public static List<Integer> spiralOrder(int[][] matrix) {

        int left = 0;
        int right = matrix[0].length-1;
        int top = 0;
        int bottom = matrix.length-1;
        ArrayList<Integer> list = new ArrayList<>(bottom*right);
        int i = 0;
        while (left <= right || top <= bottom) {
            if (i>right) break;
            while (i <= right) {
                list.add(matrix[top][i]);
                i++;
            }
            top++;
            i = top;
            if (i>bottom) break;
            while (i <= bottom) {
                list.add(matrix[i][right]);
                i++;
            }
            right--;
            i = right;
            if (i< left) break;
            while (i >= left) {
                list.add(matrix[bottom][i]);
                i--;
            }
            bottom--;
            i = bottom;
            if (i<top) break;
            while (i >= top) {
                list.add(matrix[i][left]);
                i--;
            }
            left++;
            i=left;

        }
        return list;

    }


    public static void main(String[] args) {
        int[][] nums = {{1,2,3},
                        {4,5,6},
                        {7,8,9}};
/*        int[][] nums = {{0, 1, 2, 0},
                {3, 4, 5, 2},
                {1, 3, 1, 5}};*/
        List<Integer> integers = spiralOrder(nums);

        integers.forEach(System.out::println);
    }
}
